
package com.lzx.adx.report.controller.v1.qtt;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.CZCovertQttEventTypeEnums;
import com.lzx.adx.report.enums.CZCovertXMWifiEventTypeEnums;
import com.lzx.adx.report.model.qtt.QttRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.AdPerUtil;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.lzx.adx.report.util.helper.KkHeper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 媒体:趣头条
 * 产品:TT语音(创智)
 */
@RequestMapping("/qtt/cz")
@RestController
@Slf4j
public class QttCzReportController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;


    @GetMapping("/report")
    public ResponseEntity report(QttRequest requestParams) {
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(requestParams.getDspId());
        log.info("接收到{}的请求参数为{}", accountDTO.getName(), JsonUtils.toJsonString(requestParams));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(requestParams);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(requestParams));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        String finalUrl = KkHeper.covertChuangZhiUrl(accountDTO, requestParams, reportDTO);
        log.info("账号为{},{}请求地址为{}", requestParams.getDspId(), accountDTO.getName(), finalUrl);
        //2.2调用产品，上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{} {}趣头条到智创请求上报接口响应的结果为{}", requestParams.getDspId(), accountDTO.getName(), body);
        return ResponseEntity.ok(new Result());
    }


    /**
     * 产品回传
     * 关注 注册、次留
     *
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId, String tnaEvent) throws Exception {
        log.info("趣头条创智回调信息，请求流水号{},回调类型为{}", requestId, tnaEvent);
        if (StringUtils.isBlank(requestId)) {
            log.info("趣头条创智回调信息，请求流水号空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        String qttCode = "0";
        if (StringUtils.isBlank(tnaEvent)) {
            tnaEvent="register";
        }
        if (StringUtils.isNotBlank(tnaEvent)) {
            qttCode = CZCovertQttEventTypeEnums.getQttCode(tnaEvent);
            if (StringUtils.isBlank(qttCode)) {
                log.info("事件有误,趣头条接收了创智回调信息 请求流水号{} 事件{}", requestId, tnaEvent);
                return ResponseEntity.ok(new Result());
            }
        }
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        long time = System.currentTimeMillis();
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(tnaEvent);
            reportDTO.setResultTime(String.valueOf(time));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,tnaEvent);
        } else {
            log.error("回传流水号{}，系统当前不存在", requestId);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        //如果不为空，且sspExtend
        if (StringUtils.isNotBlank(sspExtend)) {
            JSONObject jsonObject = JSONObject.parseObject(sspExtend);
            Double per = jsonObject.getDouble("per");
            if (Objects.nonNull(per)) {
                if(!AdPerUtil.randomPer(per)) {
                    log.info("dspId为{} 流水号为 {} 设置的比例为:{} 超出了比例外", reportDTO.getDspId(), reportDTO.getBizRequestId(), per);
                    return ResponseEntity.ok(new Result());
                }
            }
        }
        //3，获取回传地址，进行解码
        String decodeUrl = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        log.info("创智-趣头条转码地址为：{}", decodeUrl);
        //拼接完整的请求参数
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("op2", qttCode);
        paramsReq.put("opt_active_time", time / 1000);
        String finalUrl = decodeUrl + "&" + URLUtil.buildQuery(paramsReq, StandardCharsets.UTF_8);
        log.info("请求流水号{}回调趣头条的完整地址为：{}", requestId, finalUrl);
        String result = HttpUtil.get(finalUrl);
        log.info("请求流水号{}回调趣头条的结果为：{}", requestId, result);
        return ResponseEntity.ok(new Result());
    }



    /**
     * 产品回传
     * 关注 注册、次留
     *
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/act/callback")
    public ResponseEntity actCallBackUrl(String requestId, String tnaEvent) throws Exception {
        log.info("趣头条创智回调信息，请求流水号{},回调类型为{}", requestId, tnaEvent);
        if (StringUtils.isBlank(requestId)) {
            log.info("趣头条创智回调信息，请求流水号空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        if (StringUtils.isBlank(tnaEvent)) {
            tnaEvent="active";
        }

        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        long time = System.currentTimeMillis();
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
        } else {
            log.error("回传流水号{}，系统当前不存在", requestId);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String transformType = jsonObject.getString(tnaEvent);
        if (StringUtils.isBlank(transformType)) {
            log.info("趣头条珍爱网回调信息当前流水号：{}，事件类型{}不合法，不做数据回传", requestId, tnaEvent);
            return ResponseEntity.ok(new Result());
        }
        reportDTO.setResultType(tnaEvent);
        reportDTO.setResultTime(String.valueOf(time));
        reportDTO.setUpdateTime(new Date());
        reportService.updateData(reportDTO,tnaEvent);

        //如果不为空，且sspExtend
        if (StringUtils.isNotBlank(sspExtend)) {
            Double per = jsonObject.getDouble("per");
            if (Objects.nonNull(per)) {
                if(!AdPerUtil.randomPer(per)) {
                    log.info("dspId为{} 流水号为 {} 设置的比例为:{} 超出了比例外", reportDTO.getDspId(), reportDTO.getBizRequestId(), per);
                    return ResponseEntity.ok(new Result());
                }
            }
        }
        //3，获取回传地址，进行解码
        String decodeUrl = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        log.info("创智-趣头条转码地址为：{}", decodeUrl);
        //拼接完整的请求参数
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("op2", transformType);
        paramsReq.put("opt_active_time", time / 1000);
        String finalUrl = decodeUrl + "&" + URLUtil.buildQuery(paramsReq, StandardCharsets.UTF_8);
        log.info("请求流水号{}回调趣头条的完整地址为：{}", requestId, finalUrl);
        String result = HttpUtil.get(finalUrl);
        log.info("请求流水号{}回调趣头条的结果为：{}", requestId, result);
        return ResponseEntity.ok(new Result());
    }







    /**
     * 产品回传
     * 关注 注册、次留
     *
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/bdjs/callback")
    public ResponseEntity bdjsCallBackUrl(String requestId, String tnaEvent) {
        log.info("趣头条创智(百度极速)回调信息，请求流水号{},回调类型为{}", requestId, tnaEvent);
        if (StringUtils.isBlank(requestId)) {
            log.info("趣头条创智(百度极速)回调信息，请求流水号空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        if(StringUtils.isBlank(tnaEvent)){
            tnaEvent="active";
        }


        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        long time = System.currentTimeMillis();
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(tnaEvent);
            reportDTO.setResultTime(String.valueOf(time));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,tnaEvent);
        } else {
            log.error("回传流水号{}，系统当前不存在", requestId);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String code = jsonObject.getString(tnaEvent);
        if (StringUtils.isBlank(code)) {
            log.info("趣头条创智(百度极速)回调信息当前流水号：{}，事件类型{}不合法，不做数据回传", requestId, tnaEvent);
            return ResponseEntity.ok(new Result());
        }

        //如果不为空，且sspExtend
        if (StringUtils.isNotBlank(sspExtend)) {
            Double per = jsonObject.getDouble("per");
            if (Objects.nonNull(per)) {
                if(!AdPerUtil.randomPer(per)) {
                    log.info("dspId为{} 流水号为 {} 设置的比例为:{} 超出了比例外", reportDTO.getDspId(), reportDTO.getBizRequestId(), per);
                    return ResponseEntity.ok(new Result());
                }
            }
        }
        //3，获取回传地址，进行解码
        String decodeUrl = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        log.info("创智-趣头条转码地址为：{}", decodeUrl);
        //拼接完整的请求参数
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("op2", code);
        paramsReq.put("opt_active_time", time / 1000);
        String finalUrl = decodeUrl + "&" + URLUtil.buildQuery(paramsReq, StandardCharsets.UTF_8);
        log.info("账号{}请求流水号{}创智百度极速版回调趣头条的完整地址为：{}", reportDTO.getDspId(), requestId, finalUrl);
        String result = HttpUtil.get(finalUrl);
        log.info("账号{}请求流水号{}创智百度极速版回调趣头条的结果为：{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }

    /**
     * 是否在比例范围内
     *
     * @param per
     * @return
     */
    private static boolean shouldIdentifyAd(Double per) {
        Random random = new Random();
        double randomValue = random.nextDouble(); // 生成到1之间的随机数
        log.info("随机数为{}", randomValue);
        return randomValue > per;
    }

}
